<?php
declare (strict_types=1);

namespace app\time\controller;

use AliPay\App;
use app\common\model\Logs;
use app\common\model\Order;
use app\common\model\User;
use WeChat\Pay;

class Callback
{
    /**
     * 微信支付回调
     */
    public function wechat()
    {
        try {
            $wechat = Pay::instance(config('pay')['wechat']);
            $data = $wechat->getNotify();
            if ($data['return_code'] !== 'SUCCESS' || $data['result_code'] !== 'SUCCESS') {
                throw new \Exception('回调验证失败:' . json_encode($data));
            }
            //更新订单状态，支付完成
            $info = Order::where(['sn' => $data['out_trade_no']])->find();
            if ($info && $info->getData('status') == 1) {
                $result = Order::operation($info, User::where(['id' => $info->uid])->find(), 'wechat');
                if ($result['code'] != 1) {
                    throw new \Exception('支付失败，订单号:' . $info->sn . '-' . $result['msg']);
                }
            } else {
                throw new \Exception('未查询到订单，订单号:' . $data['out_trade_no']);
            }
            $result = $wechat->getNotifySuccessReply();

        } catch (\Exception $e) {
            Logs::write('logs/wechat.log', $e->getMessage());

            return 'FAIL';
        }

        return $result;
    }

    /**
     * 支付宝支付回调
     */
    public function alipay()
    {
        try {
            $pay = App::instance(config('pay')['alipay']);
            $data = $pay->notify();
            if (!in_array($data['trade_status'], ['TRADE_SUCCESS', 'TRADE_FINISHED'])) {
                throw new \Exception('回调验证失败:' . json_encode($data));
            }
            //更新订单状态，支付完成
            //$data['out_trade_no']订单编号
            //...执行逻辑

        } catch (\Exception $e) {
            Logs::write('logs/alipay.log', $e->getMessage());

            return 'FAIL';
        }

        return 'SUCCESS';
    }

    /**
     * 微信确认收货消息推送
     */
    public function checkSignature()
    {
        if (request()->isPost()) {
            try {
                $param = request()->param();
                if ($param['MsgType'] == 'event' && $param['Event'] == 'trade_manage_order_settlement') {
                    if (isset($param['confirm_receive_method'])) {
                        //更新订单状态，确认收货完成
                        //$param['confirm_receive_time']确认收货时间
                        //$param['merchant_trade_no']订单编号
                        //...执行逻辑
                    }
                }

            } catch (\Exception $e) {
                Logs::write('logs/confirm_receive.log', $e->getMessage());

                return false;
            }

            return 'success';
        } else {
            $signature = $_GET["signature"];
            $timestamp = $_GET["timestamp"];
            $nonce = $_GET["nonce"];
            $config = config('pay')['wechat'];
            $tmpArr = array($config['token'], $timestamp, $nonce);
            sort($tmpArr, SORT_STRING);
            $tmpStr = sha1(implode($tmpArr));
            if ($tmpStr == $signature) {
                ob_clean();
                exit(htmlspecialchars($_GET['echostr']));
            } else {
                return false;
            }
        }
    }
}